from django.shortcuts import render, HttpResponse
import json
from app01 import models

from django import forms
from django.forms import fields as Ffields
from django.forms import widgets as Fwidgets

class UserInfoModelForm(forms.ModelForm):
	is_rmb = Ffields.CharField(
		widget=Fwidgets.CheckboxInput()
	)
	class Meta:
		model = models.UserInfo
		fields = '__all__'
		# fields = ['username','user_type']
		# exclude = ['username',]
		labels = {'username':'用户名','email':'邮箱'}
		# help_texts = {'username': '。请输入英文'}
		widgets = {'username' : Fwidgets.TextInput(attrs={'class':'c1'})}
		error_messages = {
						# '__all__':{},
						'username': {'required':'不能为空'},
						'email': {'required': '不能为空'}
						}
		# field_classes = {
		# 	'email': Ffields.URLField
		# }

class UserInfoForm(forms.Form):
	username = Ffields.CharField(max_length=32,label='用户')
	email = Ffields.EmailField()
	user_type = Ffields.ChoiceField(
		choices=models.UserType.objects.values_list('id','caption')
	)

	def __init__(self, *args, **kwargs):
		super(UserInfoForm, self).__init__(*args, **kwargs)
		self.fields['user_type'].choices = models.UserType.objects.values_list('id','caption')

def index(request):
	if request.method == "GET":
		obj = UserInfoModelForm()
		return render(request, 'index.html', {'obj':obj})
	elif request.method == "POST":
		obj = UserInfoModelForm(request.POST)
		if obj.is_valid():
			obj.save()
		# print(obj.is_valid())
		# print(obj.cleaned_data)
		# print(obj.errors)
		return render(request, 'index.html', {'obj': obj})

def user_list(request):
	uli = models.UserInfo.objects.all().select_related('user_type')
	return render(request,'user_list.html',{'uli':uli})

def user_edit(request,nid):
	# models.UserInfo.objects.filter('id'=nid)
	if request.method == "GET":
		user_obj = models.UserInfo.objects.filter(id=nid).first()
		mf = UserInfoModelForm(instance=user_obj)
	if request.method == "POST":
		user_obj = models.UserInfo.objects.filter(id=nid).first()
		mf = UserInfoModelForm(request.POST, instance=user_obj)
		if mf.is_valid():
			mf.save()
		else:
			print(mf.errors.as_json())
	return render(request, 'user_edit.html', {'mf':mf, 'nid':nid})


def ajax(request):
	return render(request, 'ajax.html')

def ajax_json(request):
	ret = {'status':True, 'data':request.POST.get('username')}
	return HttpResponse(json.dumps(ret))

def upload(request):
	return render(request,'upload.html')

def upload_file(request):
	username = request.POST.get('username')
	fafa = request.FILES.get('fafa')
	import os
	img_path = os.path.join('static/imgs/',fafa.name)
	print(username,fafa)
	with open(img_path, 'wb') as f:
		for item in fafa.chunks():
			f.write(item)

	ret = {'status': True, 'data': img_path}
	return HttpResponse(json.dumps(ret))